<?php
class baiduSu {
    public $access_key;
    private $secret_key;
    private $apiurl;
    private $domain;

    function __construct() {
        $options = get_option('baidusu');
        $options = unserialize($options);
        if($options) {
            $this->access_key = $options['access_key'];
            $this->secret_key = $options['secret_key'];
        }
        $this->apiurl = 'https://api.su.baidu.com/';
        $siteurl = get_bloginfo('url');
        $this->domain = parse_url($siteurl, PHP_URL_HOST);
        $this->domain = ltrim($this->domain, 'www.');
    }

    /**
     * 拼接参数
     */
    private function build_params($params) {
        ksort($params);
        $arr = array();
        foreach($params as $key=>$val) {
            array_push($arr, $key . '=' . $val);
        }
        $arr = join('&', $arr);
        return $arr;
    }

    /**
     * 公共头
     */
    private function headers($path) {
        return [
            'X-Auth-Access-Key' => $this->access_key,
            'X-Auth-Nonce' => wp_generate_password(32, false),
            'X-Auth-Path-Info' => $path,
            'X-Auth-Signature-Method' => 'HMAC-SHA1',
            'X-Auth-Timestamp' => time(),
        ];
    }

    /**
     * 签名
     */
    private function sign($headers, $params) {
        $params = array_merge($headers, $params);
        $str = $this->build_params($params);
        $sign = hash_hmac('sha1', $str, $this->secret_key, true);
        $sign = base64_encode($sign);
        return $sign;
    }

    /**
     * 获取Zone ID
     */
    public function get_zone_id() {
        $path = 'v3/yjs/zones';
        $apiurl = $this->apiurl . $path;
        $params = array(
            'name' => $this->domain,
        );
        $headers = $this->headers($path);
        $sign = $this->sign($headers, $params);
        $headers['X-Auth-Sign'] = $sign;
        $response = wp_remote_get($apiurl, [
            'timeout' => 10,
            'headers' => $headers,
            'body' => $params,
        ]);
        
        if(is_wp_error($response)) return;
        $response = json_decode($response['body'], true);
        return isset($response['errors'][0]['message']) ? $response['errors'][0]['message'] : $response['result']['id'];
    }

    /**
     * 刷新缓存
     */
    public function refresh_cache($urls='', $type='file') {
        if(!$urls && $type=='file') {
            return 'Url不能为空';
        }

        if(!is_array($urls)) {
            $urls = array($urls);
        }

        $urls = array_slice($urls, 0, 500);
        $path = 'v3/yjs/zones/settings/purge_cache';
        $apiurl = $this->apiurl . $path;
        $params = array(
            'domain' => $this->domain,
            'purge_everything' => 0,
            'files' => join($urls, ';'),
        );

        if($type == 'all') {
            $params['purge_everything'] = 1;
            unset($params['files']);
        }
        $headers = $this->headers($path);
        $sign = $this->sign($headers, $params);
        $headers['X-Auth-Sign'] = $sign;
        $request = new WP_Http;
        $response = $request->request($apiurl, array(
            'method' => 'DELETE',
            'timeout' => 30,
            'headers' => $headers,
            'body' => $params,
        ));

        if(is_wp_error($response)) {
            return $response->get_error_message();
        }

        $response = json_decode($response['body'], true);
        if(isset($response['errors'][0]['message'])) {
            return $response['errors'][0]['message'];
        }

        return $response;
    }

    /**
     * 添加子域名
     * @param $name 主机名，不包含域名
     * @param $type 解析类型
     * @param $content 记录值
     */
    public function add_subdomain($name, $type='CNAME', $content) {
        $path = 'v3/yjs/zones/dns_records';
        $apiurl = $this->apiurl . $path;
        $params = array(
            'domain' => $this->domain,
            'name' => $name,
            'type' => $type,
            'content' => $content,
            'ttl' => 600
        );
        $headers = $this->headers($path);
        $sign = $this->sign($headers, $params);
        $headers['X-Auth-Sign'] = $sign;
        $response = wp_remote_post($apiurl, [
            'headers' => $headers,
            'body' => $params,
        ]);
        
        if(is_wp_error($response)) {
            return $response->get_error_message();
        }

        $response = json_decode($response['body'], true);
        if(isset($response['errors'][0]['message'])) {
            return $response['errors'][0]['message'];
        }

        return true;
    }
}
?>